package com.genITeam.ria.bl;

import java.util.ArrayList;
import java.util.Iterator;

import com.genITeam.ria.dao.TheadPostDAO;
import com.genITeam.ria.exception.NGFException;
import com.genITeam.ria.utility.HibernateUtils;
import com.genITeam.ria.vo.Posts;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author Administrator
 * 
 */
public class ThreadPostBL {

	
	public ThreadPostBL() {
		BasicConfigurator.configure();
	}

	Logger logger = Logger.getLogger(ThreadPostBL.class);

	/**
	 * getPost Return the Post in XML Format
	 * 
	 * @param String
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String getPost(String post_id) throws NGFException{
		Transaction tx = null;
		try {
			logger.info("Start getPost");
			TheadPostDAO postDAO = new TheadPostDAO();
			
			Session session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			Posts post = postDAO.getPost(Integer.parseInt(post_id), session);
			
			StringBuffer xml = new StringBuffer ("") ;
			xml.append("<recordset>\n");
			this.generatePostsxmlRecursive(post, xml);			
			xml.append("<record/></recordset>");
			
			System.out.print("xml = " + xml.toString()) ;
			tx.commit();
			return xml.toString() ;
			
			
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} 
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
	
		}
	}
	
	/**
	 * getPost Use the Get the Third Post of a Specifict Post Id and return in XML format
	 * 
	 * @param String
	 * 
	 * @return String
	 * @throws NGFException
	 */
	
	public String getChilds(String post_id) throws NGFException{
			Transaction tx = null;
		try {
			logger.info("Start getChilds");
			TheadPostDAO postDAO = new TheadPostDAO();
			
			Session session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			Posts post = postDAO.getChilds(Integer.parseInt(post_id), session);
			
			StringBuffer xml = new StringBuffer ("") ;
			xml.append("<recordset>\n");
			if( post != null ){
				this.generatePostsxml(post, xml);
			}
			xml.append("</recordset>");
			
			System.out.print("xml = " + xml.toString()) ;
			tx.commit();
			return xml.toString() ;
			
			
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} 
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());

		}
	}

	
	/**
	 * generatePostsxml Use the Generate the Post and return in XML format
	 * 
	 * @param String
	 * 
	 * @return none
	 * @throws NGFException
	 */
	
	public void generatePostsxml(Posts post, StringBuffer xml)  throws NGFException{
		Posts postVo = null;
		Iterator i = post.getPostses().iterator() ;
		try {
			logger.info("Start generatePostsxml");
			while (i.hasNext()){
				postVo = (Posts) i.next() ;
				xml.append("<record postId=\"" + postVo.getPostId() + "\" ");
				xml.append(" title=\"" + postVo.getTitle() + "\" ");
				xml.append(" message=\"" + postVo.getMessage() + "\" ");
				xml.append(" postDate=\"" + postVo.getPostDate() + "\"");
				xml.append(" id=\"" + post.getMember().getId()+ "\"");
				xml.append(" memberId=\"" + postVo.getMember().getNick() + "\"");
				xml.append(" psotMemberId=\"" + postVo.getMember().getId() + "\"");
				xml.append(" memberName=\"" + postVo.getMember().getFirstName() + " " + postVo.getMember().getLastName() + "\"");
				xml.append(" joinedOn=\"" + postVo.getMember().getJoinedOn() + "\"");
				xml.append(" parentId=\"" + postVo.getPosts().getPostId() + "\"");
				xml.append(" postType=\"" + postVo.getPostType() + "\"");
				xml.append(" noOfView=\"" + postVo.getNoOfView() + "\"");
				xml.append(" isLeaf=\"" + postVo.getIsLeaf() + "\"");
				xml.append(" filePath=\"" + postVo.getFilePath() + "\"");
				xml.append(" />\n");
			}
			System.out.println(xml.toString()) ;
		} catch (Exception e) {
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());

		}
	}
	
	
	/**
	 * generatePostsxmlRecursive Use the Generate the Post Data XML format Recursive
	 * 
	 * @param Posts, StringBuffer
	 * 
	 * @return none
	 * @throws NGFException
	 */	
	
	public void generatePostsxmlRecursive(Posts post, StringBuffer xml)  throws NGFException{

		if (post != null){
			try {
				logger.info("Start generatePostsxmlRecursive");
				xml.append("<record postId=\"" + post.getPostId() + "\"");
				xml.append(" title=\"" + post.getTitle() + "\" ");
				//xml.append(" message=\"" + post.getMessage() + "\"");
				xml.append(" postDate=\"" + post.getPostDate() + "\"");
				xml.append(" id=\"" + post.getMember().getId()+ "\"");
				xml.append(" memberId=\"" + post.getMember().getNick() + "\"");
				xml.append(" memberName=\"" + post.getMember().getFirstName() + " " + post.getMember().getLastName() + "\"");
				xml.append(" joinedOn=\"" + post.getMember().getJoinedOn() + "\"");
				xml.append(" parentId=\"" + post.getPosts().getPostId() + "\"");
				xml.append(" postType=\"" + post.getPostType() + "\"");
				xml.append(" noOfView=\"" + post.getNoOfView() + "\"");				
				xml.append(" filePath=\"" + post.getFilePath() + "\"");				
	
				Iterator i = post.getPostses().iterator();
				Posts p = null ;
				while(i.hasNext()) {
					p = (Posts) i.next() ;
					xml.append(" isLeaf=\"false\"");
					xml.append(" >\n");
					xml.append("<htmlMessage><![CDATA[" + post.getMessage() + "]]></htmlMessage>") ;
					generatePostsxmlRecursive(p, xml) ;
				}// end for
				
				if (p==null){
					xml.append(" isLeaf=\"true\"");
					xml.append(" >\n");
					xml.append("<htmlMessage><![CDATA[" + post.getMessage() + "]]></htmlMessage>") ;
				}
				
				xml.append("</record>");	
			} catch (Exception e) {
				logger.error("Exception = " + e.toString());
				throw new NGFException(e.getMessage());
	
			}
		}
	}
	
	
	/**
	 * getRoomList Use the Get the Chat Room List
	 * 
	 * @param none
	 * 
	 * @return String
	 * @throws NGFException
	 */	
	
	public String getRoomList() throws NGFException{
		Transaction tx = null;
		try {
			logger.info("Start getRoomList");
			
			TheadPostDAO postDAO = new TheadPostDAO();
			
			Session session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			ArrayList roomList = postDAO.getRoomList(1, session);
			
			StringBuffer xml = new StringBuffer ("") ;
			xml.append("<recordset>\n");
			this.generateRoomListXml(roomList, xml);			
			xml.append("</recordset>");
			
			System.out.print("xml = " + xml.toString()) ;
			tx.commit();
			return xml.toString() ;
			
			
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} 
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
	
		}
	}
	
	/**
	 * generateRoomListXml Use the Get the Chat Room List in XML format
	 * 
	 * @param ArrayList, StringBuffer
	 * 
	 * @return none
	 * @throws NGFException
	 */	
	
	public void generateRoomListXml(ArrayList roomList, StringBuffer xml)  throws NGFException{
		Posts postVo = null;
		Posts parentVo = null ;
		String rooms = "" ;
		try {			
			logger.info("Start generateRoomListXml");
			for (int i = 0 ; i < roomList.size(); i ++){
				postVo = (Posts) roomList.get(i) ;
				parentVo = postVo.getPosts() ;
				if (parentVo.getPostType() == 'F' &&
					rooms.indexOf(parentVo.getPostId()) == -1){
					xml.append("<item postId=\"" + parentVo.getPostId() + "\" ");
					xml.append(" title=\"" + parentVo.getTitle() + "\" ");
					xml.append(" message=\"" + parentVo.getMessage() + "\" ");
					xml.append(" />\n");
					rooms += parentVo.getPostId() + "," ;
				}
			}
			System.out.println(xml.toString()) ;
		} catch (Exception e) {
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());

		}
	}
	
	/**
	 * deleteThread Use to delete a perticular thread 
	 * 
	 * @param Posts
	 * 
	 * @return none
	 * @throws NGFException
	 */	
		
	public void deleteThread(Posts posts) throws NGFException{
		Transaction tx = null;
		try {
			logger.info("Start deleteThread");
			TheadPostDAO postDAO = new TheadPostDAO();
			
			Session session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			
			postDAO.deleteThread(posts, session);
			
			tx.commit();
					
			
		} catch (Exception e) {
			System.out.println(e.toString());
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} 
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
	
		}
	}	
	
	/**
	 * deletePost Use to delete a perticular post and its child posts 
	 * 
	 * @param Posts
	 * 
	 * @return none
	 * @throws NGFException
	 */	
			
	
	public void deletePost(Posts posts) throws NGFException{
		Transaction tx = null;
		try {
			logger.info("Start deletePost");
			TheadPostDAO postDAO = new TheadPostDAO();
			
			Session session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			
			postDAO.deletePost(posts, session);
			
			tx.commit();
					
			
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} 
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
	
		}
	}		
	
	public static void main (String[] args){
		ThreadPostBL bl = new ThreadPostBL();
		try{
			Posts posts = new Posts();
			posts.setPostId(312);
			bl.deleteThread(posts) ;
			
		}catch (Exception e){}
	}
}
